package com.yupi.springbootinit;

public class DateUtil {

    public static String nextDate(int year, int month, int day) {
        if (isValidDate(year, month, day)) {
            int nextDay = day + 1;
            int nextMonth = month;
            int nextYear = year;

            // 检查下一天是否超过当前月的最大天数
            if (nextDay > daysInMonth(nextYear, nextMonth)) {
                nextDay = 1;
                nextMonth++;

                // 检查下一月是否超过12月
                if (nextMonth > 12) {
                    nextMonth = 1;
                    nextYear++;
                }
            }

            // 格式化结果为"YYYY-MM-DD"
            return String.format("%04d-%02d-%02d", nextYear, nextMonth, nextDay);
        }

        return "无效日期";
    }

    private static boolean isValidDate(int year, int month, int day) {
        // 对输入日期进行基本验证
        return year >= 1 && year <= 9999 &&
               month >= 1 && month <= 12 &&
               day >= 1 && day <= daysInMonth(year, month);
    }

    private static int daysInMonth(int year, int month) {
        int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        // 考虑闰年的调整
        if (month == 2 && isLeapYear(year)) {
            return 29;
        }

        return daysInMonth[month];
    }

    private static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
